package com.xhh.nphm.web.controller.system;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xhh.nphm.common.annotation.RepeatSubmit;
import com.xhh.nphm.common.core.controller.BaseController;
import com.xhh.nphm.common.core.domain.AjaxResult;
import com.xhh.nphm.common.core.domain.entity.SysUser;
import com.xhh.nphm.common.core.page.TableDataInfo;
import com.xhh.nphm.common.utils.DateUtils;
import com.xhh.nphm.common.utils.ShiroUtils;
import com.xhh.nphm.common.utils.StringUtils;
import com.xhh.nphm.common.utils.bean.BeanUtils;
import com.xhh.nphm.system.domain.*;
import com.xhh.nphm.system.mapper.CommonDao;
import com.xhh.nphm.system.service.*;
import io.swagger.v3.oas.annotations.parameters.RequestBody;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/system/mMailWF/rManage")
public class MMailWFrManageController extends BaseController {
    private final String prefix = "system/mMailWF/rManage";

    @Autowired
    private CommonDao commonDao;
    @Autowired
    private MmailWorkFormService mMailWorkFormService;
    @Autowired
    private IMailGetDealService mailGetDealService;
    @Autowired
    private MMailWorkFormLogService mMailWorkFormLogService;
    @Autowired
    private OpmCrowdService opmCrowdService;
    @Autowired
    private MwfSendBackService mwfSendBackService;
    @Autowired
    private  IDeptService deptService;

    @Autowired
    private ISmsNoteService smsNoteService;

    /**
     * 进入待派-信件工单列表页面
     */
    @GetMapping("/wfDraftList")
    public ModelAndView wfDraftList() {
        return new ModelAndView(prefix + "/wfDraftList");
    }

    /**
     * 加载待派-信件工单列表信息
     */
    @PostMapping("/wfDraftListJson")
    public TableDataInfo wfDraftListJson(MmailWorkForm mmailWorkForm) {
        startPage();
        List<Map<String, Object>> list = mMailWorkFormService.wfDraftListJson(mmailWorkForm);
        return getDataTable(list);
    }

    /**
     * 进入待派-信件工单(信件受理目录下)列表页面
     */
    @GetMapping("/wfDraftListWllz")
    public ModelAndView wfDraftListWllz() {
        return new ModelAndView(prefix + "/wfDraftListWllz");
    }

    /**
     * 加载待派-信件工单(信件受理目录下)列表信息
     */
    @PostMapping("/wfDraftListWllzJson")
    public TableDataInfo wfDraftListWllzJson(MmailWorkForm mmailWorkForm) {
        startPage();
        List<Map<String, Object>> list = mMailWorkFormService.wfDraftListWllzJson(getSysUser(),mmailWorkForm);
        return getDataTable(list);
    }

    /**
     * 信件 拟派工单页面
     *
     * @param pkId
     * @param map
     * @return
     */
    @GetMapping("/wfDraftCheck/{pkId}")
    public ModelAndView wfDraftCheck(@PathVariable Integer pkId, ModelMap map) {
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(pkId);
        map.put("workFormBase", mmailWorkForm);
        map.put("originFK", mmailWorkForm.getOriginFK());
        MmailGetDealEty mmailGetDealEty = mailGetDealService.getById(mmailWorkForm.getOriginFK());
        // 图片地址
        if(mmailGetDealEty != null) {
            map.put("mmailGetDeal",mmailGetDealEty);
            map.put("isAutoExtend",mmailGetDealEty.getIsAutoExtend());
            map.put("xsysDesc", mmailGetDealEty.getXsysDesc());
            map.put("ySpare", mmailGetDealEty.getYspare());
        }
        return new ModelAndView(prefix + "/wfDraftCheck");
    }

    /**
     * 信件拟派工单
     *
     * @param mmailWorkForm
     * @return
     */
    @PostMapping("wfDraftCheckJson")
    @RequestBody
    @RepeatSubmit
    public AjaxResult wfDraftCheckJson(MmailWorkForm mmailWorkForm) {
        MmailWorkForm workForm = mMailWorkFormService.getById(mmailWorkForm.getPkId());
        SysUser user = ShiroUtils.getSysUser();
        boolean flag = false;
        if (mmailWorkForm.getOpAct() == 11) {
            UpdateWrapper<MmailWorkForm> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("CrtStepTime", new Date())
                    .set("WsUFlag", 1)
                    .set("WfLimit", mmailWorkForm.getWfLimit())
                    .set("CrtStepID", mmailWorkForm.getCrtStepId())
                    .set("CrtStepName", mmailWorkForm.getCrtStepName())
                    .eq("PkId", mmailWorkForm.getPkId());
            flag = mMailWorkFormService.update(null, updateWrapper);
            UpdateWrapper<MmailGetDealEty> getDealEtyUpdateWrapper = new UpdateWrapper<>();
            getDealEtyUpdateWrapper.set("StateFlag", 155)
                    .set("StateDesc", "审定工单")
                    .set("OpenX", mmailWorkForm.getOpenX())
                    .set("AutoGetFlag", 0).eq("PkId", mmailWorkForm.getOriginFK());
            mailGetDealService.update(null, getDealEtyUpdateWrapper);
            if (flag) {
                MMailWorkFormLog etyLog = new MMailWorkFormLog();
                etyLog.setWfId(Integer.valueOf(mmailWorkForm.getPkId()));
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                etyLog.setLogTime(new Date());
                etyLog.setOpAction("审核工单");
                etyLog.setOpBtnID(-1);
                etyLog.setWsDesc("核定工单");
                etyLog.setWsOpen(1);
                etyLog.setOpDesc("核定工单");
                etyLog.setEffectFlag(-1);
                mMailWorkFormLogService.save(etyLog);
            }
            if ((11 == mmailWorkForm.getFromTel().length()) && (mmailWorkForm.getFromTel().startsWith("1"))) {
                OpmCrowd etyMsg = new OpmCrowd();
                String msgCnt = "成都12345温馨提示：您的来信已受理（流水号：{0}；提取码：{1}），可以通过网站（http://12345.chengdu.gov.cn）进行查询，谢谢。";
                msgCnt = msgCnt.replace("{0}", workForm.getWsCode()).replace("{1}", workForm.getWsKey());

                etyMsg.setFlagOrigin(21);
                etyMsg.setWorkFormPK(Integer.parseInt(mmailWorkForm.getPkId()));
                etyMsg.setIptUserNo(user.getUserNo());
                etyMsg.setIptWorker(user.getUserName());
                etyMsg.setIptTime(new Date());
                etyMsg.setFlagSort("101");
                etyMsg.setMsgPhone(mmailWorkForm.getFromTel());
                etyMsg.setMsgCnnt(msgCnt);
                etyMsg.setMsgSign("");
                etyMsg.setFlagSend(0);
                opmCrowdService.save(etyMsg);
            }
        } else {
            UpdateWrapper<MmailWorkForm> updateWrapper = new UpdateWrapper<>();
            updateWrapper.set("CrtStepTime", new Date())
                    .set("WsUFlag", 1)
                    .set("WfLimit", mmailWorkForm.getWfLimit())
                    .set("CrtStepID", mmailWorkForm.getCrtStepId())
                    .set("CrtStepName", mmailWorkForm.getCrtStepName())
                    .eq("PkId", mmailWorkForm.getPkId());
            flag = mMailWorkFormService.update(null, updateWrapper);
            if (flag) {
                MMailWorkFormLog etyLog = new MMailWorkFormLog();
                etyLog.setWfId(Integer.valueOf(mmailWorkForm.getPkId()));
                etyLog.setOpDeptNo(user.getDeptId().toString());
                etyLog.setOpDeptName(user.getDeptName());
                etyLog.setOpUserNo(user.getUserNo());
                etyLog.setOpUserName(user.getUserName());
                etyLog.setLogTime(new Date());
                etyLog.setOpAction("作废工单");
                etyLog.setOpBtnID(-1);
                etyLog.setWsDesc("作废工单");
                etyLog.setWsOpen(0);
                etyLog.setOpDesc("作废工单");
                etyLog.setEffectFlag(-1);
                mMailWorkFormLogService.save(etyLog);
            }
        }
        return toAjax(flag);
    }

    /**
     * 拟办部门页面
     */
    @GetMapping("/sendDept/{pkId}")
    public ModelAndView sendDept(@PathVariable Integer pkId,Integer pid, ModelMap map) {
        SysUser user = ShiroUtils.getSysUser();
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(pkId);
        MwfSendBack mwfSendBack = new MwfSendBack();
        mwfSendBack.setSdeptId(user.getDeptId().toString());
        mwfSendBack.setSdeptName(user.getDeptName());
        mwfSendBack.setSuserNo(user.getUserNo());
        mwfSendBack.setSuserName(user.getUserName());
        map.put("mmailWorkForm", mmailWorkForm);
        map.put("wfId", mmailWorkForm.getPkId());
        map.put("mailPk", mmailWorkForm.getOriginFK());
        map.put("sdeptName", user.getDept().getDeptShort());
        map.put("sdeptId", mwfSendBack.getSdeptId());
        map.put("suserName", mwfSendBack.getSuserName());
        map.put("suserNo", mwfSendBack.getSuserNo());
        map.put("deptId", user.getDeptId());
        map.put("sendTime", DateUtils.getTime());
        map.put("pid", pid);
        return new ModelAndView(prefix + "/sendDept");
    }

    /**
     * 拟办部门新增数据
     * 未签收模块的转派
     * 签收页面的转派
     * 回复页面的增派
     * @param mwfSendBack
     * @return
     */
    @RepeatSubmit
    @PostMapping("sendDeptJson")
    public AjaxResult sendDeptJson(MwfSendBack mwfSendBack,Integer smsInform,String workFormNo,String zpFlag) {
        if (IS_GAOXIN()){
            return sendDeptJson_gxq(mwfSendBack,smsInform,workFormNo,zpFlag);
        }else{
            return sendDeptJson_general(mwfSendBack,smsInform,workFormNo);
        }
    }

    public AjaxResult sendDeptJson_general(MwfSendBack mwfSendBack,Integer smsInform,String workFormNo) {
        //保存影响结果
        boolean flag = false;
        mwfSendBack.setOriLevel(1);
        Integer pid = mwfSendBack.getPid();
        if(pid == null || pid <= 0) {
            //不用每个地方都从页面把pid传够了，容易绕晕，但父id不是百分百准确
            QueryWrapper<MwfSendBack> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("top 1 pkId");
            queryWrapper.eq("wfId", mwfSendBack.getWfId());
            queryWrapper.eq("SBDeptId",getSysUser().getDeptId());
            queryWrapper.orderByDesc("pkId");
            List<MwfSendBack> list = mwfSendBackService.list(queryWrapper);
            if(list != null && list.size() > 0) {
                pid = list.get(0).getPkId();
            }
        }
        mwfSendBack.setPid(pid);
        //拟派多个部门
        if(mwfSendBack.getSbdeptId().indexOf(',') != -1){
            String[] ids = mwfSendBack.getSbdeptId().split(",");
            String[] names = mwfSendBack.getSbdeptName().split(",");
            String sendDesc = mwfSendBack.getSendDesc();
            for (int i = 0; i < ids.length; i++) {
                mwfSendBack.setSendDesc(sendDesc.replace(mwfSendBack.getSbdeptName(),names[i]));
                mwfSendBack.setSbdeptId(ids[i]);
                mwfSendBack.setSbdeptName(names[i]);
                flag = mwfSendBackService.save(mwfSendBack);
            }
        }
        //拟派一个部门
        else {
            flag = mwfSendBackService.save(mwfSendBack);
        }
        //更新父级派单状态 注意mwfSendBack的pkId是插入数据库返回的Id
        commonDao.proMsubBackState(mwfSendBack.getWfId(),mwfSendBack.getPkId());
        //发短信
        if(StringUtils.isNotNull(smsInform) && smsInform == 1){
            smsNoteService.sendSmsNote(mwfSendBack.getSbdeptId(),workFormNo, "派单");
        }
        return toAjax(flag);
    }

    public AjaxResult sendDeptJson_gxq(MwfSendBack mwfSendBack,Integer smsInform,String workFormNo,String zpFlag) {
        //保存影响结果
        boolean flag = false;
        String sdeptNO = mwfSendBack.getSdeptId(),sdeptName = mwfSendBack.getSdeptName();
        Integer pid = mwfSendBack.getPid();
        mwfSendBack.setOriLevel(1);
        if(pid == null || pid <= 0) {
            //不用每个地方都从页面把pid传够了，容易绕晕，但父id不是百分百准确
            QueryWrapper<MwfSendBack> queryWrapper = new QueryWrapper<>();
            queryWrapper.select("top 1 pkId");
            queryWrapper.eq("wfId", mwfSendBack.getWfId());
            queryWrapper.eq("SBDeptId",getSysUser().getDeptId());
            queryWrapper.orderByDesc("pkId");
            List<MwfSendBack> list = mwfSendBackService.list(queryWrapper);
            if(list != null && list.size() > 0) {
                pid = list.get(0).getPkId();
            }
        }
        mwfSendBack.setPid(pid);
        mwfSendBack.setPromisesTime(mwfSendBack.getBackLimit());
        //拟派多个部门
        if(mwfSendBack.getSbdeptId().indexOf(',') != -1){
            String[] ids = mwfSendBack.getSbdeptId().split(",");
            String[] names = mwfSendBack.getSbdeptName().split(",");
            String[] zpFlags = zpFlag.split(",");
            for (int i = 0; i < ids.length; i++) {
                mwfSendBack.setSendDesc("请 "+names[i]+" 调查处理后直接与来话人联系，并将处理结果抄复我办。请注意来话人个人信息保密。");
                mwfSendBack.setSbdeptId(ids[i]);
                mwfSendBack.setSbdeptName(names[i]);
                //重置
                mwfSendBack.setPid(pid);
                mwfSendBack.setSdeptId(sdeptNO);
                mwfSendBack.setSdeptName(sdeptName);
                if (zpFlags[i].equals("10")){
                    mwfSendBack.setSendSpare("1");//直派
                    flag = directWF(mwfSendBack);
                }else {
                    flag = mwfSendBackService.save(mwfSendBack);
                }
                commonDao.proMsubBackState(mwfSendBack.getWfId(),mwfSendBack.getPkId());
            }
        } else {//拟派一个部门
            if (zpFlag != null && zpFlag.equals("0")){
                flag = mwfSendBackService.save(mwfSendBack);
            }else {
                flag = directWF(mwfSendBack);
            }
            //更新父级派单状态 注意mwfSendBack的pkId是插入数据库返回的Id
            commonDao.proMsubBackState(mwfSendBack.getWfId(),mwfSendBack.getPkId());
        }
        //发短信
        if(StringUtils.isNotNull(smsInform) && smsInform == 1){
            smsNoteService.sendSmsNote(mwfSendBack.getSbdeptId(),workFormNo, "派单");
        }
        return toAjax(flag);
    }

    //直派工单
    public boolean directWF(MwfSendBack sendBack){
        String deptNo ="",deptName="";
        //查询直派部门的上级部门
        Map<String, Object> handleDept = commonDao.queryDirectParentDept(sendBack.getSbdeptId());
        if (!handleDept.isEmpty()) {
            deptNo = (String)handleDept.get("noUnit");
            deptName = (String)handleDept.get("deptShort");
        }
        MwfSendBack newSendBack = new MwfSendBack();
        BeanUtils.copyBeanProp(newSendBack,sendBack);
        newSendBack.setSendState(23);//已派下级
        newSendBack.setSbdeptId(deptNo);
        newSendBack.setSbdeptName(deptName);
        newSendBack.setSendDesc("请 "+deptName+" 调查处理后直接与来话人联系，并将处理结果抄复我办。请注意来话人个人信息保密。");
        mwfSendBackService.save(newSendBack);
        sendBack.setSdeptId(deptNo);
        sendBack.setSdeptName(deptName);
        sendBack.setPid(newSendBack.getPkId());
        return mwfSendBackService.save(sendBack);
    }

    /**
     * 拟办部门列表数据
     *
     * @param wfId
     * @return
     */
    @PostMapping("/sendDeptListJson/{wfId}")
    public TableDataInfo sendDeptListJson(@PathVariable Integer wfId) {
        List<MwfSendBack> list = mwfSendBackService.sendDeptListJson(wfId);
        return getDataTable(list);
    }

    /**
     * 承办单位页面
     *
     * @return
     */
    @GetMapping("/deptAllS")
    public ModelAndView deptAllS() {
        return new ModelAndView(prefix + "/deptAllS");
    }

    /**
     * 根据id 进行多选删除 和单个删除
     *
     * @param ids
     * @return
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String... ids) {
        return toAjax(mwfSendBackService.removeByIds(Arrays.asList(ids)));
    }

    /**
     * 派单部门编辑页面
     */
    @GetMapping("/sendDeptEdit/{wfId}/{sbid}")
    public ModelAndView sendDeptEdit(@PathVariable Integer wfId, @PathVariable Integer sbid, ModelMap map) {
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(wfId);
        map.put("mmailWorkForm", mmailWorkForm);
        MwfSendBack mwfSendBack = mwfSendBackService.getById(sbid);
        map.put("mwfSendBack", mwfSendBack);
        return new ModelAndView(prefix + "/sendDeptEdit");
    }

    /**
     * 派单部门编辑保存数据
     *
     * @param
     * @return
     */
    @PostMapping("sendDeptEditJson")
    @RequestBody
    @RepeatSubmit
    public AjaxResult sendDeptEditJson(MwfSendBack mwfSendBack) {

        UpdateWrapper<MwfSendBack> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("SeqCode", mwfSendBack.getSeqCode())
                .set("SeqName", mwfSendBack.getSeqName())
                .set("SendTime", mwfSendBack.getSendTime())
                .set("SBDeptID", mwfSendBack.getSbdeptId())
                .set("SBDeptName", mwfSendBack.getSbdeptName())
                .set("SortCode", mwfSendBack.getSortCode())
                .set("SortName", mwfSendBack.getSortName())
                .set("DealCode", mwfSendBack.getDealCode())
                .set("DealName", mwfSendBack.getDealName())
                .set("SendDesc", mwfSendBack.getSendDesc())
                .set("BackLimit", mwfSendBack.getBackLimit())
                .set("SendRemark", mwfSendBack.getSendRemark())
                .set("isDelay", mwfSendBack.getIsDelay())
                .eq("PkId", mwfSendBack.getPkId());
        boolean flag = mwfSendBackService.update(null, updateWrapper);
        if (flag) {
            SysUser user = ShiroUtils.getSysUser();
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(mwfSendBack.getWfId());
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            String temp = "";
            temp = "调整办理部门及要求（" + mwfSendBack.getSbdeptName() + "）派单信息";
            etyLog.setOpAction("修改");
            //etyLog.setOpBtnId(-1);
            etyLog.setOpBtnID(-1);
            etyLog.setWsDesc(temp);
            etyLog.setWsOpen(1);
            etyLog.setOpDesc(temp);
            etyLog.setEffectFlag(-1);
            mMailWorkFormLogService.save(etyLog);
        }
        return toAjax(flag);
    }

    /**
     * 信件工单直接答复页面
     */
    @GetMapping("/mWFormOver/{pkId}")
    public ModelAndView mWFormOver(@PathVariable Integer pkId, ModelMap map) {
        MmailWorkForm mmailWorkForm = mMailWorkFormService.getById(pkId);
        map.put("mmailWorkForm", mmailWorkForm);
        map.put("originFK", mmailWorkForm.getOriginFK());
        MmailGetDealEty mmailGetDealEty = mailGetDealService.getById(mmailWorkForm.getOriginFK());
        map.put("xsysDesc", mmailGetDealEty.getXsysDesc());
        return new ModelAndView(prefix + "/mWFormOver");
    }

    /**
     * 信件工单 直接答复数据
     * @param mmailWorkForm
     * @return
     */
    @PostMapping("/mWFormOverJson")
    @RequestBody
    public AjaxResult mWFormOverJson(MmailWorkForm mmailWorkForm) {
        SysUser user = ShiroUtils.getSysUser();
        UpdateWrapper<MmailWorkForm> updateWrapper = new UpdateWrapper<>();
        updateWrapper.set("DOverTime", new Date())
                .set("CrtStepTime", new Date())
                .set("RecordFlag", 29)
                .set("RecordTime", new Date())
                .set("RecUserNo", user.getUserNo())
                .set("RecUserName",user.getUserName())
                .set("IptWorkNo",mmailWorkForm.getIptWorkNo())
                .set("IptWorker",mmailWorkForm.getIptWorker())
                .set("DOverDesc",mmailWorkForm.getDOverDesc())
                .eq("PkId",mmailWorkForm.getPkId());
        boolean flag = mMailWorkFormService.update(null, updateWrapper);
        if (flag){
            MMailWorkFormLog etyLog = new MMailWorkFormLog();
            etyLog.setWfId(Integer.parseInt(mmailWorkForm.getPkId()));
            etyLog.setOpDeptNo(user.getDeptId().toString());
            etyLog.setOpDeptName(user.getDeptName());
            etyLog.setOpUserNo(user.getUserNo());
            etyLog.setOpUserName(user.getUserName());
            etyLog.setLogTime(new Date());
            etyLog.setOpAction("强制结束");
            etyLog.setOpBtnID(-1);
            etyLog.setWsDesc("结束工单。");
            etyLog.setWsOpen(1);
            etyLog.setOpDesc("强制结束:" + mmailWorkForm.getDOverDesc());
            etyLog.setEffectFlag(-1);
            mMailWorkFormLogService.save(etyLog);
        }
        return toAjax(flag);
    }

    /**
     * 派发下级相关的更新状态和日志
     * @param sender 拟派工单信息
     */
    //TODO
    @PostMapping("/sendSon")
    public void sendSon(MwfSendBack sender){
        String desc = "";
        //当前用户登录信息
        SysUser user = getSysUser();
        //更新工单当前信息
        UpdateWrapper<MmailWorkForm> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PkId", sender.getWfId());
        updateWrapper.set("WsUFlag", 1);
        updateWrapper.set("CrtStepId", 400);
        updateWrapper.set("CrtStepName", "市级部门处理中");
        updateWrapper.set("CrtStepTime", DateUtils.getNowDate());
        mMailWorkFormService.update(null, updateWrapper);
        //更新当前派单情况 新增签收日期
        UpdateWrapper<MwfSendBack> wrapper = new UpdateWrapper<>();
        wrapper.eq("PkId", sender.getPkId());
        wrapper.set("SendState", 23);
        MwfSendBack oldSendBack = mwfSendBackService.getById(sender.getPkId());
        if(oldSendBack != null && oldSendBack.getGetTime() == null) {
            wrapper.set("getTime", new Date());
            wrapper.set("getPerson", user.getUserNo());
            wrapper.set("getPerTel", user.getNoTel());
        }
        mwfSendBackService.update(null, wrapper);

        MMailWorkFormLog etyLog = new MMailWorkFormLog();
        //[tWorkFormBase]PkId
        etyLog.setWfId(sender.getWfId());
        etyLog.setOpDeptNo(user.getDeptId().toString());
        etyLog.setOpDeptName(user.getDeptName());
        etyLog.setOpUserNo(user.getUserNo());
        etyLog.setOpUserName(user.getUserName());
        etyLog.setOpAction("派单到下级部门");
        etyLog.setOpBtnID(-1);
        desc = sender.getSbdeptName();
        etyLog.setWsDesc("转办工单（" + desc + "）");
        etyLog.setWsOpen(1);
        etyLog.setOpDesc("提交到下级部门（" + desc + "）");
        etyLog.setEffectFlag(1);
        mMailWorkFormLogService.save(etyLog);
    }

    /**
     * 批量派单
     * @return
     */
    @PostMapping("/batchSendToSon")
    public AjaxResult batchSendToSon(MwfSendBack mwfSendBack,String pkIds, String wfIds, String mailPks) {
        boolean opResult = false;
        if(StringUtils.isNotNull(pkIds)&&StringUtils.isNotNull(wfIds)){
            if(pkIds.contains(",") && wfIds.contains(",") && mailPks.contains(",")){
                String[] pkId = pkIds.split(",");
                String[] wfId = wfIds.split(",");
                String[] mailPk = mailPks.split(",");
                for (int i = 0; i < pkId.length; i++) {
                    mwfSendBack.setPkId(0);
                    mwfSendBack.setWfId(Integer.parseInt(wfId[i]));
                    mwfSendBack.setMailPk(Integer.parseInt(mailPk[i]));
                    opResult = sendDept(mwfSendBack,pkId[i]);
                }
            }else{
                mwfSendBack.setPkId(0);
                mwfSendBack.setWfId(Integer.parseInt(wfIds));
                mwfSendBack.setMailPk(Integer.parseInt(mailPks));
                opResult = sendDept(mwfSendBack,pkIds);
            }
        }else{
            return error();
        }
        return toAjax(opResult);
    }


    public boolean sendDept(MwfSendBack mwfSendBack,String pkId) {
        //保存影响结果
        boolean flag = false;
        MwfSendBack sendEty = new MwfSendBack();
        BeanUtils.copyBeanProp(sendEty, mwfSendBack);
        sendEty.setOriLevel(1);
        //拟派多个部门
        if(sendEty.getSbdeptId().indexOf(',') != -1){
            String[] ids = sendEty.getSbdeptId().split(",");
            String[] names = sendEty.getSbdeptName().split(",");
            for (int i = 0; i < ids.length; i++) {
                sendEty.setPkId(0);
                String sendDesc = sendEty.getSendDesc();
                sendEty.setSendDesc(sendDesc.replace(sendEty.getSbdeptName(),names[i]));
                sendEty.setSbdeptId(ids[i]);
                sendEty.setSbdeptName(names[i]);
                flag = mwfSendBackService.save(sendEty);
            }
        }
        //拟派一个部门
        else {
            flag = mwfSendBackService.save(sendEty);
        }
        if(StringUtils.isNotNull(pkId)) {
            sendSonLog(mwfSendBack,pkId);
        }
        return flag;
    }

    public void sendSonLog(MwfSendBack mwfSendBack,String pkId){
        String desc = "";
        //当前用户登录信息
        SysUser user = getSysUser();
        //更新工单当前信息
        UpdateWrapper<MmailWorkForm> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("PkId",mwfSendBack.getWfId());
        updateWrapper.set("WsUFlag", 1);
        updateWrapper.set("CrtStepId", 400);
        updateWrapper.set("CrtStepName", "市级部门处理中");
        updateWrapper.set("CrtStepTime", DateUtils.getNowDate());
        mMailWorkFormService.update(null, updateWrapper);
        //更新当前派单情况 新增签收日期
        UpdateWrapper<MwfSendBack> wrapper = new UpdateWrapper<>();
        wrapper.eq("PkId", pkId);
        wrapper.set("SendState", 23);
        MwfSendBack oldSendBack = mwfSendBackService.getById(pkId);
        if(oldSendBack != null && oldSendBack.getGetTime() == null) {
            wrapper.set("getTime", new Date());
            wrapper.set("getPerson", user.getUserNo());
            wrapper.set("getPerTel", user.getNoTel());
        }
        mwfSendBackService.update(null, wrapper);
        MMailWorkFormLog etyLog = new MMailWorkFormLog();
        //[tWorkFormBase]PkId
        etyLog.setWfId(mwfSendBack.getWfId());
        etyLog.setOpDeptNo(user.getDeptId().toString());
        etyLog.setOpDeptName(user.getDeptName());
        etyLog.setOpUserNo(user.getUserNo());
        etyLog.setOpUserName(user.getUserName());
        etyLog.setOpAction("派单到下级部门");
        etyLog.setOpBtnID(-1);
        desc = mwfSendBack.getSbdeptName();
        etyLog.setWsDesc("转办工单（" + desc + "）");
        etyLog.setWsOpen(1);
        etyLog.setOpDesc("提交到下级部门（" + desc + "）");
        etyLog.setEffectFlag(1);
        mMailWorkFormLogService.save(etyLog);
    }

}